<?php
namespace app\v6\controller;

use think\Controller;
use think\Db;
use think\Request;

/**
 * 数据同步控制器
 */
class DataSync extends Controller
{
    /**
     * 初始化方法，设置 CORS 头
     */
    protected function initialize()
    {
        parent::initialize();
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
        header("Access-Control-Allow-Headers: Content-Type, Authorization");
        
        // 处理 OPTIONS 预检请求
        if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
            exit();
        }
    }
    
    /**
     * 预览症状数据
     */
    public function previewSymptoms(Request $request)
    {
        try {
            $data = $request->post('data', []);
            
            if (empty($data)) {
                return json(['code' => 1, 'msg' => '数据不能为空']);
            }

            // 获取所有分类
            $categories = Db::name('symptom_categories')
                ->where('is_active', 1)
                ->column('name_zh_cn', 'id');
            
            // 获取已存在的症状
            $existingSymptoms = Db::name('symptoms')
                ->column('name_zh_cn');

            $result = [];
            foreach ($data as $item) {
                // 查找分类ID
                $categoryId = array_search($item['category_name'], $categories);
                
                if ($categoryId === false) {
                    $item['status'] = 'error';
                    $item['statusText'] = '分类不存在';
                } elseif (in_array($item['name_zh_cn'], $existingSymptoms)) {
                    $item['status'] = 'exists';
                    $item['statusText'] = '已存在';
                } else {
                    $item['status'] = 'ready';
                    $item['statusText'] = '待导入';
                }
                
                $item['category_id'] = $categoryId ?: 0;
                $result[] = $item;
            }

            return json(['code' => 0, 'msg' => '预览成功', 'data' => $result]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '预览失败：' . $e->getMessage()]);
        }
    }

    /**
     * 导入症状数据
     */
    public function importSymptoms(Request $request)
    {
        try {
            $data = $request->post('data', []);
            
            if (empty($data)) {
                return json(['code' => 1, 'msg' => '数据不能为空']);
            }

            $success = 0;
            $skipped = 0;
            $failed = 0;
            $errors = [];

            Db::startTrans();
            try {
                foreach ($data as $item) {
                    // 检查分类是否存在
                    $categoryId = 0;
                    if (!empty($item['category_name'])) {
                        $category = Db::name('symptom_categories')
                            ->where('name_zh_cn', $item['category_name'])
                            ->where('is_active', 1)
                            ->find();
                        
                        if (!$category) {
                            $failed++;
                            $errors[] = "症状 {$item['name_zh_cn']} 导入失败：分类 {$item['category_name']} 不存在";
                            continue;
                        }
                        $categoryId = $category['id'];
                    }
                    
                    // 检查症状是否已存在
                    $exists = Db::name('symptoms')
                        ->where('name_zh_cn', $item['name_zh_cn'])
                        ->find();
                    
                    if ($exists) {
                        $skipped++;
                        continue;
                    }

                    // 插入数据
                    $insertData = [
                        'category_id' => $categoryId,
                        'name_zh_cn' => $item['name_zh_cn'],
                        'name_en_us' => $item['name_en_us'],
                        'name_ja_jp' => $item['name_ja_jp'],
                        'name_be_by' => $item['name_be_by'],
                        'is_active' => 1,
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s')
                    ];

                    $result = Db::name('symptoms')->insert($insertData);
                    
                    if ($result) {
                        $success++;
                    } else {
                        $failed++;
                        $errors[] = "症状 {$item['name_zh_cn']} 插入失败";
                    }
                }

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                throw $e;
            }

            return json([
                'code' => 0,
                'msg' => '导入完成',
                'data' => [
                    'success' => $success,
                    'skipped' => $skipped,
                    'failed' => $failed,
                    'errors' => $errors
                ]
            ]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '导入失败：' . $e->getMessage()]);
        }
    }

    /**
     * 预览汤药数据
     */
    public function previewFormulas(Request $request)
    {
        try {
            $data = $request->post('data', []);
            
            if (empty($data)) {
                return json(['code' => 1, 'msg' => '数据不能为空']);
            }

            // 获取所有症状（用于匹配）
            $symptoms = Db::name('symptoms')
                ->where('is_active', 1)
                ->column('name_zh_cn', 'id');

            $result = [];
            foreach ($data as $item) {
                $hasError = false;
                $warnings = [];

                // 处理主症
                $mainSymptomIds = [];
                if (!empty($item['main_symptoms'])) {
                    $mainSymptomNames = array_filter(array_map('trim', explode(';', $item['main_symptoms'])));
                    foreach ($mainSymptomNames as $name) {
                        $symptomId = array_search($name, $symptoms);
                        if ($symptomId !== false) {
                            $mainSymptomIds[] = $symptomId;
                        } else {
                            $warnings[] = "主症 '{$name}' 不存在";
                            $hasError = true;
                        }
                    }
                }

                // 处理兼症
                $sideSymptomIds = [];
                if (!empty($item['side_symptoms'])) {
                    $sideSymptomNames = array_filter(array_map('trim', explode(';', $item['side_symptoms'])));
                    foreach ($sideSymptomNames as $name) {
                        $symptomId = array_search($name, $symptoms);
                        if ($symptomId !== false) {
                            $sideSymptomIds[] = $symptomId;
                        } else {
                            $warnings[] = "兼症 '{$name}' 不存在";
                            $hasError = true;
                        }
                    }
                }

                $item['main_symptom_ids'] = implode(',', $mainSymptomIds);
                $item['side_symptom_ids'] = implode(',', $sideSymptomIds);
                
                if ($hasError) {
                    $item['status'] = 'error';
                    $item['statusText'] = '症状不存在';
                } elseif (empty($mainSymptomIds) && empty($sideSymptomIds)) {
                    $item['status'] = 'warning';
                    $item['statusText'] = '无症状';
                } else {
                    $item['status'] = 'ready';
                    $item['statusText'] = '待导入';
                }
                
                $item['warnings'] = $warnings;
                $result[] = $item;
            }

            return json(['code' => 0, 'msg' => '预览成功', 'data' => $result]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '预览失败：' . $e->getMessage()]);
        }
    }

    /**
     * 导入汤药数据
     */
    public function importFormulas(Request $request)
    {
        try {
            $data = $request->post('data', []);
            
            if (empty($data)) {
                return json(['code' => 1, 'msg' => '数据不能为空']);
            }

            $success = 0;
            $skipped = 0;
            $failed = 0;
            $errors = [];

            Db::startTrans();
            try {
                foreach ($data as $item) {
                    // 检查是否已存在
                    $exists = Db::name('formulas')
                        ->where('name_zh_cn', $item['name_zh_cn'])
                        ->find();
                    
                    if ($exists) {
                        $skipped++;
                        continue;
                    }

                    // 处理症状ID（如果是文本，需要转换）
                    $mainSymptomIds = isset($item['main_symptom_ids']) ? $item['main_symptom_ids'] : '';
                    $sideSymptomIds = isset($item['side_symptom_ids']) ? $item['side_symptom_ids'] : '';
                    
                    // 如果是症状名称字符串，需要转换为ID
                    if (!empty($item['main_symptoms']) && empty($mainSymptomIds)) {
                        $mainSymptomIds = $this->convertSymptomNamesToIds($item['main_symptoms']);
                    }
                    if (!empty($item['side_symptoms']) && empty($sideSymptomIds)) {
                        $sideSymptomIds = $this->convertSymptomNamesToIds($item['side_symptoms']);
                    }

                    // 插入数据
                    $insertData = [
                        'name_zh_cn' => $item['name_zh_cn'],
                        'name_en_us' => $item['name_en_us'],
                        'name_ja_jp' => $item['name_ja_jp'],
                        'name_be_by' => $item['name_be_by'],
                        'main_symptom_ids' => $mainSymptomIds,
                        'side_symptom_ids' => $sideSymptomIds,
                        'is_active' => 1,
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s')
                    ];

                    $result = Db::name('formulas')->insert($insertData);
                    
                    if ($result) {
                        $success++;
                    } else {
                        $failed++;
                        $errors[] = "方剂 {$item['name_zh_cn']} 插入失败";
                    }
                }

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                throw $e;
            }

            return json([
                'code' => 0,
                'msg' => '导入完成',
                'data' => [
                    'success' => $success,
                    'skipped' => $skipped,
                    'failed' => $failed,
                    'errors' => $errors
                ]
            ]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '导入失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 将症状名称字符串转换为症状ID字符串
     * @param string $symptomNames 症状名称，用分号分隔
     * @return string 症状ID，用逗号分隔
     */
    private function convertSymptomNamesToIds($symptomNames)
    {
        if (empty($symptomNames)) {
            return '';
        }
        
        // 获取所有症状
        $symptoms = Db::name('symptoms')
            ->where('is_active', 1)
            ->column('id', 'name_zh_cn');
        
        // 分割症状名称
        $names = array_filter(array_map('trim', explode(';', $symptomNames)));
        $ids = [];
        
        foreach ($names as $name) {
            if (isset($symptoms[$name])) {
                $ids[] = $symptoms[$name];
            }
        }
        
        return implode(',', $ids);
    }
}
